<?php

namespace app\home\controller;

use app\common\controller\Home;
use PHPMailer;
use think\Cookie;

class User extends Home
{
    public function __construct()
    {
        parent::__construct();

        $this->RegionModel = model('Region');

        $this->CollectModel = model('User.Collect');

        $this->CommentModel = model('Post.Comment');
        //加载 home 模型 如果home里面没有 在去公共的模块里面去
        $this->UserModel = model('User.User');   // /User/User.php
        $this->PostModel = model('Post.Post');
        $this->RecordModel = model('User.Record');

    }

    // 个人中心
    public function index()
    {
       

        //查询地区表的省份数据
       $province = $this->RegionModel->where(['code' => $this->LoginUser['province']])->find();
       
       //赋值
       $this->assign('province', $province['province']);

       $params = $this->request->param('userid',0);


       //查询帖子
       $postses = $this->PostModel->where(['userid' =>$this->LoginUser['id']])->order('createtime','desc')->paginate(10);
               
       $postssun = $this->PostModel->where(['userid' =>$this->LoginUser['id']])->order('createtime','desc')->select();

       //分页调用
       $pagestr = $postses->render();

       $this->assign([
           'posts' => $postses,
           'pagestr' => $pagestr,
           'postssun' => count($postssun),
       ]);

       if($params){
           $user = $this->UserModel->where(['id'=>$params])->find();
           

           $this->assign([
               'user' => $user,
           ]);
          return $this->fetch('user');
       }else{
           return $this->fetch();
       }
    }

    // 基本设置
    public function profile()
    {
        $bg = $this->request->param('bg', '');
        if ($this->request->isPost()) {
            // 接收隐藏域的值
            $action = $this->request->param('action', '');
            // 修改资料
            if ($action == 'profile') {
                // 昵称
                $nickname = $this->request->param('nickname', '');

                // 性别
                $sex = $this->request->param('sex', 0);

                // 省份
                $provinces = $this->request->param('province', 0);

                // 市
                $citys = $this->request->param('city', 0);

                // 区
                $districts = $this->request->param('district', 0);

                // 个人签名
                $content = $this->request->param('content', '');

                // 封装更新数据
                $data = [
                    'id' => $this->LoginUser['id'],
                    'nickname' => $nickname,
                    'province' => $provinces,
                    'city' => $citys,
                    'district' => $districts,
                    'content' => $content,
                    'sex' => $sex
                ];

                // 更新数据表
                $result = $this->UserModel->isUpdate(true)->save($data);

                if ($result === FALSE) {
                    $this->error($this->UserModel->getError());
                    exit;
                } else {
                    $data = [
                        'id' => $this->LoginUser['id'],
                        'nickname' => $nickname,
                        'email' => $this->LoginUser['email'],
                        'vip' => $this->LoginUser['vip'],
                        'auth' => $this->LoginUser['auth'],
                        // isset => null 
                        'avatar' => !empty($this->LoginUser['avatar']) ? $this->LoginUser['avatar'] : '/static/home/res/images/avatar/default.png',
                        'cover' => !empty($this->LoginUser['cover']) ? $this->LoginUser['cover'] : '/static/home/res/images/cover.jpg'
                    ];

                    // 认证成功后
                    cookie('LoginUser', $data);
                    $this->success('更新资料成功', url('home/user/index'));
                    exit;
                }
            }
            // 修改密码
            if ($action == "password") {

                //当前密码
                $nowpass = $this->request->param('nowpass', '');
                $password = $this->request->param('pass', '');
                $repass = $this->request->param('repass', '');

                //盐
                $salt = $this->LoginUser['salt'];

                //加密
                $nowpass = md5(trim($nowpass) . $salt);

                if ($nowpass != $this->LoginUser['password']) {
                    $this->error('当前密码输入错误');
                    exit;
                }

                //判断是否等于原来的密码
                $newpass = md5(trim($password) . $salt);

                if ($newpass == $this->LoginUser['password']) {
                    $this->error('新密码不能设置为当前密码');
                    exit;
                }

                //判断密码和确认密码是否一致
                if ($password != $repass) {
                    $this->error('密码和确认密码不一致');
                    exit;
                }

                //重新生成一下密码盐
                // $salt = randstr(10);

                $password = md5(trim($password) . $salt);

                //组装数据
                $data = [
                    'id' => $this->LoginUser['id'],
                    'salt' => $salt,
                    'password' => $password
                ];

                //调用模型的更新方法
                $result = $this->UserModel->isUpdate(true)->save($data);

                if ($result === FALSE) {
                    $this->error($this->UserModel->getError());
                    exit;
                } else {
                    $this->success('密码修改成功');
                    exit;
                }
            }
            // 上传头像
            if ($action == 'avatar') {
                $avatar = upload('avatar');

                if ($avatar === FALSE) {
                    $this->error('上传失败');
                    exit;
                }

                // 封装数组
                $data = [
                    'id' => $this->LoginUser['id'],
                    'avatar' => $avatar
                ];

                // 更新数据库
                $result = $this->UserModel->isUpdate(true)->save($data);

                if ($result === FALSE) {
                    @is_file(ROOT_PATH . 'public' . DS . $avatar) && @unlink(ROOT_PATH . 'public' . DS . $avatar);

                    $this->error($this->UserModel->getError());
                    exit;
                } else {
                    @is_file(ROOT_PATH . 'public' . DS . $this->LoginUser['avatar']) && @unlink(ROOT_PATH . 'public' . DS . $this->LoginUser['avatar']);

                    $data = [
                        'id' => $this->LoginUser['id'],
                        'nickname' => $this->LoginUser['nickname'],
                        'email' => $this->LoginUser['email'],
                        'vip' => $this->LoginUser['vip'],
                        'auth' => $this->LoginUser['auth'],
                        // isset => null 
                        'avatar'=>$data['avatar'] ? $data['avatar'] : '/assets/home/images/avatar.png',
                        'cover'=>is_file($this->LoginUser['cover']) ? '/'.$this->LoginUser['cover'] : '/assets/home/images/back.jpg',
                    ];

                    // 认证成功后
                    cookie('LoginUser', $data);
                    $this->success('更新成功', url('home/user/index'));
                    exit;
                }
            }
            // 上传封面
            if ($action == 'cover') {
                $avatar = upload('cover');

                if ($avatar === FALSE) {
                    $this->error('上传失败');
                    exit;
                }

                // 封装数组
                $data = [
                    'id' => $this->LoginUser['id'],
                    'cover' => $avatar
                ];

                // 更新数据库
                $success = $this->UserModel->isUpdate(true)->save($data);

                if ($success == FALSE) {
                    //上传上来的图片删除了
                    @is_file($data['cover']) && @unlink($data['cover']);

                    $this->error('修改封面失败');
                    exit;
                } else {
                    //修改成功后，将原来的图片删除
                    $avatar = ltrim($this->LoginUser['cover'], "/");
                    @is_file($avatar) && @unlink($avatar);

                    //设置一个保存cookie信息
                    $cookie = [
                        'id' => $this->LoginUser['id'],
                        'nickname' => $this->LoginUser['nickname'],
                        'vip' => $this->LoginUser['vip'],
                        'auth' => $this->LoginUser['auth'],
                        'cover'=>is_file($data['cover']) ? '/'.$data['cover'] : '/assets/home/images/back.jpg',
                        'avatar'=>$this->LoginUser['avatar'] ? $this->LoginUser['avatar'] : '/assets/home/images/avatar.png',
                    ];


                    // 认证成功后
                    Cookie::set('LoginUser', $cookie);

                    $this->success('更新成功', url('home/user/index'));
                    exit;
                }
            }
        }

        // 查询省份
        $province = $this->RegionModel->where(['grade' => 1])->select();

        if (empty($this->LoginUser['province'])) {
            $city = [];
        } else {
            $city = $this->RegionModel->where(['parentid' => $this->LoginUser['province']])->select();
        }

        if (empty($this->LoginUser['city'])) {
            $district = [];
        } else {
            $district = $this->RegionModel->where(['parentid' => $this->LoginUser['city']])->select();
        }
        // halt($province);

        $this->assign([
            'province' => $province,
            'city' => $city,
            'district' => $district,
            $this->assign('bg',$bg)
        ]);
        return $this->fetch();
    }

    // 查询省 / 市
    public function area()
    {
        $code = $this->request->param('code', 0);

        $data = $this->RegionModel->where(['parentid' => $code])->select();

        $result = [
            'code' => 0,
            'msg' => '未知信息',
            'data' => null,
        ];

        if ($data === FALSE) {
            $result['msg'] = '查询失败';
            echo json_encode($result);
            exit;
        } else {
            $result = [
                'code' => 1,
                'msg' => '查询成功',
                'data' => $data,
            ];
            echo json_encode($result);
            exit;
        }

        // echo json_encode($code);

    }

    // 邮箱验证
    public function email()
    {
        $email = $this->request->param('email', '');

        $result = [
            'code' => 0,
            'msg' => '未知信息',
            'data' => null
        ];

        if (empty($email)) {
            $result['msg'] = '邮箱不能为空';
            echo json_encode($result);
            exit;
        }

        // 把邮箱加密
        $email = md5($email);

        $msg = "<a href='http://www.ask.com/index.php/home/index/email?email=$email'>点击认证</a>";

        // G:\phpstudy_pro\WWW\ask\extend\
        // echo EXTEND_PATH;
        // 引用SMTP服务
        require_once(EXTEND_PATH . 'phpmail/class.phpmailer.php');
        // couiazbjizfffjai  => 授权码
        // JYCBYAJWJWDWBDUY
        // 实例化发送邮件类
        $mail = new PHPMailer(true);

        // 启用smtp
        $mail->IsSMTP(true);
        // SMTP服务器 qq => smtp.qq.com
        $mail->Host = "smtp.qq.com";
        // 开启smtp认证
        $mail->SMTPAuth = true;
        // 发送内容支持HTML
        $mail->IsHTML(true);
        // 邮箱用户名 => SMTP账号
        $mail->Username = "1871142580@qq.com";
        // 密码 => 授权码
        $mail->Password = "xvlpjiwrmhfiidfa";
        // 设置SMTP服务端口 上线后需要服务器开启这个端口 
        $mail->Port = 465;

        // ssl协议
        $mail->SMTPSecure = 'ssl';

        // 发件人
        $mail->From = "1871142580@qq.com";

        // 发件人名称
        $mail->FromName = "ask论坛";

        //回复人
        $mail->AddReplyTo("1871142580@qq.com", "ask论坛");

        // 收件人的邮箱和名称
        $mail->AddAddress($this->LoginUser['email'], $this->LoginUser['nickname']);
        // 邮件主题 => 标题
        $mail->Subject  = "ask论坛激活认证";

        //设置多少个字符换行 80字符
        $mail->WordWrap = 50;

        // 发送内容
        // $mail->Body = $msg;
        $mail->MsgHTML($msg);

        // 发送内容支持HTML
        $mail->IsHTML(true);

        // 发送
        $res = $mail->Send();

        // 发送是否成功
        if ($res === FALSE) {
            $result['msg'] = '邮件发送失败';
            echo json_encode($result);
            exit;
        } else {
            $result['code'] = 1;
            $result['msg'] = '邮件发送成功';
            echo json_encode($result);
            exit;
        }
    }

    //用户中心 我的评论
    public function comment()
    {
        $bg = $this->request->param('bg', '');

        $userid = $this->LoginUser['id'];

        $commitsum = $this->CommentModel->where(['userid' => $userid])->order('createtime','desc')->select();

        $commits = $this->CommentModel->where(['userid' => $userid])->order('createtime','desc')->paginate(10);
        

        //分页调用
        $pagestr = $commits->render();

        // var_dump($commits);
        // exit;

        $this->assign([
            'commits'=>$commits,
            'pagestr' => $pagestr,
            'commsun' => count($commitsum),
            //侧栏选中样式渲染
            'bg' => $bg,
        ]);

        //渲染模板
        return $this->fetch();
    }

    //用户中心 我的消费记录
    public function record(){
        $bg = $this->request->param('bg', '');

        $userid = $this->LoginUser['id'];
        
        $recordsum = $this->RecordModel->where(['userid' => $userid])->order('createtime','desc')->select();

        $records = $this->RecordModel->where(['userid' => $userid])->order('createtime','desc')->paginate(10);

        //分页调用
        $pagestr = $records->render();

        // var_dump($records);
        // exit;

        $this->assign([
            'recordsum' => count($recordsum),
            'pagestr' => $pagestr,
            'records' => $records,
            //侧栏选中样式渲染
            'bg' => $bg,
        ]);
        
        return $this->fetch();
    }
}
